#include <unistd.h>
#include <sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include <iostream>
#include "utils.h"
#include "data_struct.h"
#include "config.h"

using namespace std;
const off_t  NEXT_FILE_SEQ_POS = 72;

int getFileSeq(int fd)
{
	int iOldSeq;
	lseek(fd, NEXT_FILE_SEQ_POS, SEEK_SET);
	if (read(fd, &iOldSeq, sizeof(iOldSeq))<0)
		return -1;
	return iOldSeq;
}

int setFileSeq(int fd, int iNewSeq)
{
	lseek(fd, NEXT_FILE_SEQ_POS, SEEK_SET);
	if (write(fd, &iNewSeq, sizeof(iNewSeq))<0)
		return -1;
	return 0;
}


int main(int argc,char** argv){
	if(argc != 3){
		cout << "usage:" << argv[0]  << " [conf path] [next file seq]" << endl;
		return -1;
	}

	//read config file first
	CConfig *cfg=CConfig::getInstance();
	if(cfg->ParseConfig(argv[1])!=0){
		cout<<"parse conf = ["<<argv[1]<<"] failed"<<endl;
		return -1;
	}

	//open the the first data file to modify head's nextFileSeq
	char filename[255];
	MAKE_FILE_NAME(filename, cfg->GetStrVal("BTREE","path"),cfg->GetStrVal("BTREE","prefix"), 0);
	
	int fd = open(filename, O_LARGEFILE | O_RDWR, 0644);
	if (fd<0)
	{
		cout<<"can not open file:"<<filename<<endl;
		return -1;
	}

	//seek in the right position and modify head's nextFileSeq
	int iNewSeq = atoi(argv[2]);
	int iOldSeq = getFileSeq(fd);
	cout<<"old seq is "<<iOldSeq<<", and new seq is "<<iNewSeq<<", are you sure to modify?y/n    ";
	char c='n';
	cin>>c;
	if (c=='y')
	{
		setFileSeq(fd, iNewSeq);
		int iCurSeq = getFileSeq(fd);
		cout << "set nexFileSeq of the file:"<<filename<<" head success, current seq:" <<iCurSeq<< endl;
	}
	return 0;

}

